package swim.sessionbeans;

import java.util.HashSet;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import swim.entitybeans.Admin;
import swim.entitybeans.RegisteredUser;

/**
 * Session Bean implementation class Search
 */
@Stateless
@RemoteBinding(jndiBinding="Search/remote")
public class Search implements SearchRemote, SearchLocal {

	@PersistenceContext(unitName="swim")
	private EntityManager manager;
	
	@SuppressWarnings("unchecked")
	public Set<RegisteredUser> searchUser(String name){
		HashSet<RegisteredUser> usc = new HashSet<RegisteredUser>();
		Query q = manager.createQuery("FROM RegisteredUser u WHERE (LOCATE(u.firstname,:name) > 0 OR LOCATE(u.lastname,:name) > 0) OR u.username =:name OR  u.email =:name");
		q.setParameter("name", name);
		usc.addAll(q.getResultList());
		return usc;
	}


	@SuppressWarnings("unchecked")
	public Set<RegisteredUser> searchForAbility(String ability){
		HashSet<RegisteredUser> usc = new HashSet<RegisteredUser>();
		Query q = manager.createQuery("SELECT u FROM RegisteredUser u JOIN u.skills t WHERE  t.name like :ability");		
		q.setParameter("ability", "%" + ability + "%");
		usc.addAll(q.getResultList());
		return usc;		
	}
	
	@SuppressWarnings("unchecked")
	public Set<RegisteredUser> searchByUsername(String username){
		HashSet<RegisteredUser> result = new HashSet<RegisteredUser>();
		try {
			Query q = manager.createQuery("FROM RegisteredUser u WHERE u.username =:username");
			q.setParameter("username", username);
			result.addAll(q.getResultList());			
			return result;
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return result;
		}
	}
	
	@SuppressWarnings("unchecked")
	public Set<RegisteredUser> searchByMail(String mail){
		HashSet<RegisteredUser> result = new HashSet<RegisteredUser>();
		try {
			Query q = manager.createQuery("FROM RegisteredUser u WHERE u.email =:mail");
			q.setParameter("mail", mail);
			result.addAll(q.getResultList());			
			return result;
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return result;
		}
	}


	@Override
	public RegisteredUser searchById(long id) {
		return manager.find(RegisteredUser.class, id);
	}


	@Override
	public Admin searchAdminById(long id) {
		return manager.find(Admin.class, id);
	}

}
